//
//  RW_PlayerViewController.m
//  SleepApp
//
//  Created by chuangqi on 2021/3/30.
//  Copyright © 2021 RiceWang. All rights reserved.
//

#import "RW_PlayerViewController.h"
#import "RW_SingleModel.h"
#import "RW_UserSingleModel.h"
#import "RW_SongModel.h"
#import "RW_PlayerView.h"
#import "RW_Players.h"
#import <MediaPlayer/MediaPlayer.h>
#import "RW_CopyrightShowView.h"

@interface RW_PlayerViewController ()
@property (nonatomic,strong) RW_Players *wlclass_players_model;
@property (nonatomic,strong) RW_PlayerView *wlclass_view;

/** 音频列表 */
@property (nonatomic,strong) NSArray<RW_SongModel *> *songList;
@end

@implementation RW_PlayerViewController
#pragma mark -- 单利方法重写 单利播放器为当前正在播放的音频或者列表 --
static RW_PlayerViewController *class = nil;
+ (instancetype)sharedInstance {
    @synchronized(self) {
        if (class == nil) {
            class = [[self alloc] init];
        }
    }
    return class;
}
#pragma mark -- 功能逻辑方法 --
/** 替换掉当前的播放控制器 */
+(void)realodPlayerViewController:(RW_PlayerViewController *)vc{
    [class releseViewController];
    class = nil;
    class = vc;
}
/** 停止播放器功能，主要用于和其他类型播放器互斥 */
+(void)stopPlayerAudio{
    if (![RW_PlayerViewController sharedInstance].wlclass_players_model.songList.count){
        return;
    }
    [[[RW_PlayerViewController sharedInstance] wlclass_players_model] stopPlay];
}
/** 当前单利播放器的播放状态 */
+(BOOL)playingStatus{
    if (![RW_PlayerViewController sharedInstance].wlclass_players_model.songList.count){
        return Player_Status_Type_Default;
    }
    return [[RW_PlayerViewController sharedInstance] wlclass_players_model].play_status_type == Player_Status_Type_Playing;
}
#pragma mark -- 跳转方法 --
/** 打开当前播放列表 */
+(void)pushSingleFromVc:(UIViewController *)fromVc{
    NSLog(@"%@",[RW_PlayerViewController sharedInstance]);
    if (![RW_PlayerViewController sharedInstance].wlclass_players_model.songList.count){
        [SVProgressHUD showError_wl:@"当前没有正在播放的音频"];
        return;
    }
    [fromVc.navigationController pushViewController:[RW_PlayerViewController sharedInstance] animated:YES];
}
/** 打开公共播放列表 */
+(void)pushSingleId:(NSString *)singleId fromVc:(UIViewController *)fromVc{
    [SVProgressHUD show_wl];
    [[[RW_SingleModel getSingleSongListId:singleId] then:^id _Nullable(RW_SingleModel * _Nullable value) {
        if (value.list.count){
            [self showVcSongList:value.list fromVc:fromVc];
        } else {
            [SVProgressHUD showError_wl:@"操作失败"];
        }
        return nil;
    }] catch:^(NSError * _Nonnull error) {
        [SVProgressHUD showError_wl:@"操作失败"];
    }];
}
/** 打开个人播放列表 */
+(void)pushUserSingleId:(NSString *)singleId fromVc:(UIViewController *)fromVc{
    [SVProgressHUD show_wl];
    [[[RW_UserSingleModel getUserSingleSongListId:singleId] then:^id _Nullable(RW_UserSingleModel * _Nullable value) {
        if (value.list.count){
            [self showVcSongList:value.list fromVc:fromVc];
        } else {
            [SVProgressHUD showError_wl:@"操作失败"];
        }
        return nil;
    }] catch:^(NSError * _Nonnull error) {
        [SVProgressHUD showError_wl:@"操作失败"];
    }];
}
/** 打开单个歌曲播放 */
+(void)pushSongId:(NSString *)songId fromVc:(UIViewController *)fromVc{
    [SVProgressHUD show_wl];
    [[[RW_SongModel getSongInfoId:songId] then:^id _Nullable(RW_SongModel * _Nullable value) {
        if (value){
            [self showVcSongList:@[value] fromVc:fromVc];
        } else {
            [SVProgressHUD showError_wl:@"操作失败"];
        }
        return nil;
    }] catch:^(NSError * _Nonnull error) {
        [SVProgressHUD showError_wl:@"操作失败"];
    }];
}
//打开一个新的播放器
+(void)showVcSongList:(NSArray<RW_SongModel *> *)songList fromVc:(UIViewController *)fromVc{
    [SVProgressHUD dismiss_wl];
    RW_PlayerViewController *vc = [[RW_PlayerViewController alloc]init];
    vc.songList = songList;
    NSLog(@"%@",vc);
    [fromVc.navigationController pushViewController:vc animated:YES];
}


#pragma mark -- 页面逻辑 --
/** 子控制器初始化视图 */
- (void)initView{
    [self.contentFullView addSubview:self.wlclass_view];
    [self.wlclass_view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    [self setNavigationColor:UIColor.clearColor navigationLienColor:UIColor.clearColor];
}
/** 子控制第一次加载数据了 */
- (void)initData{
    self.wlclass_players_model.songList = self.songList;
}
/** 子控制每次展示页面刷新数据 */
- (void)initReloadData{
    
}
#pragma mark -- 父控制器方式
-(UIImage *)set_rightBarButtonItemWithImage{
    return [UIImage svgName:@"public_author_big_icon"];
}
-(void)right_button_event:(UIButton *)sender{
    RW_CopyrightShowView.init_wl()
    .maskAlpha_wl(.5f)
    .addData_wl(self.wlclass_players_model.play_song)
    .show_wl();
}


#pragma mark - 设置锁屏界面的信息
/** 这个方法在开始播放音乐的时候手动调用 */
-(void)setupLockScreenPlaySongInfo:(RW_SongModel *)playingMusic duration:(NSInteger)duration{
   // 1.获取锁屏界面中心
   MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
   
   // 2.设置展示的信息
   NSMutableDictionary *playingInfo = [NSMutableDictionary dictionary];
   // 设置歌曲标题
   [playingInfo setObject:playingMusic.name forKey:MPMediaItemPropertyAlbumTitle];
   // 设置歌手
   [playingInfo setObject:@"" forKey:MPMediaItemPropertyArtist];
   // 设置封面
   MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithBoundsSize:CGSizeMake(100, 100) requestHandler:^UIImage * _Nonnull(CGSize size) {
//        [UIImage imageNamed:playingMusic.cover]
       return [UIImage svgName:@"tabbar_mine"];
   }];
   [playingInfo setObject:artWork forKey:MPMediaItemPropertyArtwork];
   // 设置歌曲播放的总时长
   [playingInfo setObject:@(duration) forKey:MPMediaItemPropertyPlaybackDuration];
   
   playingInfoCenter.nowPlayingInfo = playingInfo;
   
   // 3.让应用程序可以接受远程事件
   [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
#pragma mark -- 锁屏播放通知监听
/** 监听远程事件 */
-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay: // 播放
            [self.wlclass_players_model beginPlay];
            break;
        case UIEventSubtypeRemoteControlPause: // 暂停
            //开始播放内容
            [self.wlclass_players_model pausePlay];
            break;
        case UIEventSubtypeRemoteControlNextTrack: // 下一首
            [self.wlclass_players_model nextPlayIndex];
            break;
        case UIEventSubtypeRemoteControlPreviousTrack: // 上一首
            [self.wlclass_players_model lessPlayIndex];
            break;
        default:
            break;
    }
}
#pragma mark -- 懒加载
-(RW_PlayerView *)wlclass_view{
    if (!_wlclass_view){
        _wlclass_view = [[RW_PlayerView alloc]init];
        _wlclass_view.roowViewController = self;
        _wlclass_view.wlclass_players_model = self.wlclass_players_model;
    }
    return _wlclass_view;
}
-(RW_Players *)wlclass_players_model{
    if (!_wlclass_players_model){
        _wlclass_players_model = [[RW_Players alloc]init];
        /** 当前播放状态 只读 */
        [RACObserve(_wlclass_players_model, play_status_type) subscribeNext:^(id play_status_type_t) {
            Player_Status_Type play_status_type = (Player_Status_Type)[play_status_type_t intValue];
            NSLog(@"当前状态：%lu",(unsigned long)play_status_type);
            [self changePlayStatus:play_status_type];
        }];
    }
    return _wlclass_players_model;
}
/** 修改播放文本图标状态 */
-(void)changePlayStatus:(Player_Status_Type)type{
    switch (type) {
        case Player_Status_Type_InitData://数据初始化完成
            [self setupLockScreenPlaySongInfo:self.wlclass_players_model.play_song
                                     duration:self.wlclass_players_model.play_all_second];
        default:
            break;
    }
}

#pragma mark -- 释放内存组件 --
/** 播放器控制器销毁流程 */
-(void)releseViewController{
    if (![[RW_PlayerViewController sharedInstance] isEqual:self]){
        [_wlclass_view releaseVM];
        [_wlclass_players_model releaseVM];
        [_wlclass_view removeFromSuperview];
        _wlclass_view = nil;
        _wlclass_players_model = nil;
        _songList = nil;
    }
}
@end
